package rjeutsky.database.jpa;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import rjeutsky.database.jpa.models.JPAUser;
import rjeutsky.models.User;

public class JPAUserRepository extends BaseCRUDDomainRepository<User> {

	public JPAUserRepository(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
	
	@Override
	public List<User> query() throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<User> users =  JPAUser.getUsers(session.createQuery("from JPAUser").list());
		
		session.getTransaction().commit();
		session.close();
		
		return users;
	}

	@Override
	public void create(User item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAUser user = new JPAUser();
		user.setLogin(item.getLogin());
		user.setPassword(item.getPassword());
		user.setSalt(item.getSalt());
		session.save(user);
		item.setId(user.getId());
		
		session.getTransaction().commit();
		session.close();
		
	}

	@Override
	public User read(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		User user = null;
		
		JPAUser jpaUser = (JPAUser) session.get(JPAUser.class, id);
		if (jpaUser != null) {
			user = jpaUser.getUser();
		}
		
		session.getTransaction().commit();
		session.close();
		return user;
	}

	@Override
	public void update(User item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAUser user = JPAUser.getJPAUser(session, item);
		if (user != null) {
			user.setLogin(item.getLogin());
			user.setPassword(item.getPassword());
			user.setSalt(item.getSalt());
		}
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void delete(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAUser user = (JPAUser) session.get(JPAUser.class, id);
		if (user != null) {
			session.delete(user);
		}
		
		session.getTransaction().commit();
		session.close();
		
	}

}
